package ee.propaganda.gparrot.client.app;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

import ee.propaganda.gparrot.client.app.ajax.AuthService;
import ee.propaganda.gparrot.client.app.ajax.AuthServiceAsync;
import ee.propaganda.gparrot.client.app.ajax.NotLoggedInException;
import ee.propaganda.gparrot.client.app.ajax.WaveService;
import ee.propaganda.gparrot.client.app.ajax.WaveServiceAsync;
import ee.propaganda.gparrot.client.model.DataService;
import ee.propaganda.gparrot.client.model.DataServiceAsync;
import ee.propaganda.gparrot.client.model.LoginInfo;


public class AppServices {
	private static AppServices singletonInstance;
	private AuthServiceAsync authService;
	private DataServiceAsync dataService;
	private WaveServiceAsync waveService;
	private LoginInfo loginInfo = null;
	private HandlerManager eventBus;
	
	private AppServices(){
		eventBus = new HandlerManager(null);
	}
	
	public HandlerManager getEventBus() {
		return eventBus;
	}

	public static AppServices getInstance(){
		if (singletonInstance == null)
			singletonInstance = new AppServices();
		return singletonInstance;
		
	}

	public AuthServiceAsync getAuthService() {
		if (authService == null)
			authService = GWT.create(AuthService.class);
		return authService;
	}
	
	public DataServiceAsync getDataService() {
		if (dataService == null)
			dataService = GWT.create(DataService.class);
		return dataService;
	}
	
	public WaveServiceAsync getWaveService() {
		if (waveService == null)
			waveService = GWT.create(WaveService.class);
		return waveService;
	}
	
	public void handleError(Throwable error) { 
		Window.alert(error.getMessage()); 
		if (error instanceof NotLoggedInException) 
			Window.Location.replace(loginInfo.getLogoutUrl()); 
		  
	}

	public void setLoginInfo(LoginInfo result) {
		this.loginInfo = result;
		
	}

	public LoginInfo getLoginInfo() {
		if (loginInfo == null){
			authService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() { 
				public void onFailure(Throwable error) {
				}
				public void onSuccess(LoginInfo result) { 					
					setLoginInfo(result);
				}
			});
		}
		return loginInfo;
	}

}
